package com.xyyl.patient.controller;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.xyyl.patient.common.utils.SysConfigUtils;
import com.xyyl.patient.core.constant.AppEnum;
import com.xyyl.patient.core.controller.BaseController;
import com.xyyl.patient.core.support.Pager;
import com.xyyl.patient.core.util.ResponseBodyResult;
import com.xyyl.patient.core.util.StringUtils;
import com.xyyl.patient.entity.doctor.Disease;
import com.xyyl.patient.entity.doctor.Doctor;
import com.xyyl.patient.entity.doctor.DoctorPatientRelation;
import com.xyyl.patient.entity.question.DoctorEvaluate;
import com.xyyl.patient.service.doctor.DoctorService;
import com.xyyl.patient.service.user.UserService;

/**
 * @author chengjun
 * @ClassName: DoctorController
 * @Description: 医生管理Controller
 * 1.医生查询列表
 * 2.医生详情
 * 4.医生评价
 * 5.添加医生为好友
 * @date 2017年8月16日
 */
@RestController
@RequestMapping("/doctor")
public class DoctorController extends BaseController {


    @Autowired
    private DoctorService doctorService;

    @Autowired
    private UserService userService;

    /**
     * @param @return 参数
     * @return JSONObject    返回类型
     * @throws
     * @Title: queryDetail
     * @Description: 找医生首页
     */
    @RequestMapping(value = "/findDoctorIndex", method = RequestMethod.POST)
    public JSONObject queryDetail() {
        Pager pager = super.initPage();

        try {
            List<Doctor> doctorList = doctorService.getDoctor(pager);
            List<Disease> diseaseList = doctorService.getDisease();
            Map<String,Object> mapResult =Maps.newHashMap();
            mapResult.put("diseaseList", diseaseList);
            mapResult.put("doctorList", doctorList);
            return ResponseBodyResult.success(mapResult);

        } catch (Exception e) {
            return ResponseBodyResult.error("医生列表查询失败!", e);

        }

    }
    @RequestMapping(value = "/gethops", method = RequestMethod.GET)
    public JSONObject gethops() {
        List<Map<String,Object>> objectMap = doctorService.getHosp();
        return ResponseBodyResult.success(objectMap);
    }
    @RequestMapping(value = "/getDept", method = RequestMethod.GET)
    public JSONObject getDept(@RequestParam(value="pass",required = false) Integer hospitalid) {
        List<Map<String,Object>> objectMap = doctorService.getDept(hospitalid);
        return ResponseBodyResult.success(objectMap);
    }
    /*医生详情评价列表*/
    @RequestMapping(value = "/getDoctorEvaluate", method = RequestMethod.POST)
    public JSONObject getDoctorEvaluate() {
        Pager pager = super.initPage();

        try {
            List<DoctorEvaluate> doctorEvaluateList =doctorService.getDoctorEvaluate(pager);
            return ResponseBodyResult.success(doctorEvaluateList);

        } catch (Exception e) {
            return ResponseBodyResult.error("医生评分查询失败!", e);

        }

    }
    //医生详情页
    @RequestMapping(value = "/doctorDetail", method = RequestMethod.POST)
    public JSONObject doctorDetail(@RequestParam Integer doctorId) {
        try {
            Doctor doctor = doctorService.getDoctorById(doctorId);
            if(doctor==null){
                doctor =doctorService.getDoctorinfo(doctorId);
            }
            if (StringUtils.isEmpty(doctor.getAvatar())) {
				String defaultDoctor = SysConfigUtils
						.getConfigValue(AppEnum.sysConfig.DOCTOR_AVATAR_ALIYUN_URL.name());
				doctor.setAvatar(defaultDoctor);
			}
            List<Disease> diseaseList = doctorService.getDiseaseByDoctorId(doctorId);
            Map<String,Object> mapResult =Maps.newHashMap();
            mapResult.put("diseaseList", diseaseList);
            mapResult.put("doctor", doctor);
            return ResponseBodyResult.success(mapResult);
        } catch (Exception e) {
            return ResponseBodyResult.error("医生详情查询失败!", e);

        }

    }

    /**
     * @param @return 参数
     * @return JSONObject    返回类型
     * @throws
     * @Title: doctorEvaluate
     * @Description: 评价医生
     */
    @RequestMapping(value = "/doctorEvaluate", method = RequestMethod.POST)
    public JSONObject doctorEvaluate(@RequestBody DoctorEvaluate doctorEvaluate) {
        String nowDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()).toString();
        doctorEvaluate.setCreatetime(nowDate);
        try {
            Integer result = doctorService.saveDoctorEvaluate(doctorEvaluate);
            if (result.intValue() == 1) {
                return ResponseBodyResult.success("评价成功");
            } else {
                return ResponseBodyResult.fail("评价失败");
            }
        } catch (Exception e) {
            return ResponseBodyResult.error("评价失败!", e);

        }

    }


    /**
     * @param @return 参数
     * @return JSONObject    返回类型
     * @throws
     * @Title: addDoctorFriends
     * @Description: 患者添加医生好友
     */

    @RequestMapping(value = "/addDoctorFriends", method = RequestMethod.POST)
    public JSONObject addDoctorFriends(@RequestParam Integer doctorid, @RequestParam Integer  patientid , DoctorPatientRelation doctorPatientRelation) {
        try {
            if (doctorPatientRelation.getDoctorid() != null && doctorPatientRelation.getPatientid() != null) {
                String nowDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()).toString();
                DoctorPatientRelation doctorPatientRelation1 =doctorService.getDoctorFriends(doctorPatientRelation);
                Integer resutle;

                if(doctorPatientRelation1 !=null){
                    doctorPatientRelation1.setUpdatetime(nowDate);
                    resutle = userService.setRelation(doctorPatientRelation1);
                    return ResponseBodyResult.fail("你已经关注过此医生了");
                }else {
                	Doctor doctor = doctorService.getDoctorById(doctorid);
                	if(doctor==null){
                        String moblie = doctorService.queryDoctorMoblieById(doctorid);
                        if(!moblie.isEmpty()){
                            doctor =new Doctor();
                            doctor.setIsfinevisit(1);
                        }else {
                            return ResponseBodyResult.fail("关注失败,医生未认证");
                        }

                    }
                	Map<String, Object> map=new HashMap<>();
                	map.put("patientid", patientid);
                	map.put("isfinevisit", doctor.getIsfinevisit());
                    doctorPatientRelation.setUpdatetime(nowDate);
                    resutle =doctorService.saveAndDelete(map,doctorPatientRelation);
                }
                if (resutle.intValue() > 0) {
                    doctorService.updateDoctorConcern(doctorid,1);
                    return ResponseBodyResult.success("关注成功");
                } else {
                    return ResponseBodyResult.fail("关注失败");
                }
            } else {
                return ResponseBodyResult.fail("缺少参数");
            }
        } catch (Exception e) {
            return ResponseBodyResult.error("关注失败!", e);

        }


    }

    @RequestMapping(value = "/myAccount", method = RequestMethod.GET)
    public JSONObject myAccount(Long id) {


        return ResponseBodyResult.success();
    }

    @RequestMapping(value = "/myPrescriptionList", method = RequestMethod.GET)
    public JSONObject myprescriptionlist(Long id) {


        return ResponseBodyResult.success();
    }

    @RequestMapping(value = "/feedback", method = RequestMethod.GET)
    public JSONObject feedback(Long id) {


        return ResponseBodyResult.success();
    }
    
    /**
     * @param @return 参数
     * @return JSONObject    返回类型
     * @throws
     * @Title: queryDetail
     * @Description: 找医生订单页面
     */
    @RequestMapping(value = "/chooseDoctorIndex", method = RequestMethod.POST)
    public JSONObject queryDoctorlist() {
        Pager pager = super.initPage();

        try {
            System.out.println(pager);
            List<Doctor> doctorList = doctorService.getDoctor(pager);
            Map<String,Object> mapResult =Maps.newHashMap();
            mapResult.put("doctorList", doctorList);
            return ResponseBodyResult.success(mapResult);

        } catch (Exception e) {
            return ResponseBodyResult.error("医生列表查询失败!", e);

        }

    }
    
    /**
     * @param @return 参数
     * @return JSONObject    返回类型
     * @throws
     * @Title: deleteDoctorFriends
     * @Description: 患者取消医生的关注
     */

    @RequestMapping(value = "/deleteDoctorFriends", method = RequestMethod.POST)
    public JSONObject deleteDoctorFriends(@RequestParam Integer doctorid, @RequestParam Integer  patientid) {
        try {
                DoctorPatientRelation doctorPatientRelation=new DoctorPatientRelation();
                doctorPatientRelation.setDoctorid(doctorid);
                doctorPatientRelation.setPatientid(patientid);
                DoctorPatientRelation doctorPatientRelation1 =doctorService.getDoctorFriends(doctorPatientRelation);
                Integer resutle;
                if(doctorPatientRelation1 ==null){
                    return ResponseBodyResult.fail("你尚未关注此医生");
                }else {
                    resutle = doctorService.deleteByID(doctorPatientRelation1.getId());
                }
                if (resutle.intValue() > 0) {
                	doctorService.deleteIMByParameter( doctorPatientRelation);
                    return ResponseBodyResult.success("取消关注成功");
                } else {
                    return ResponseBodyResult.fail("取消关注失败");
                }
        } catch (Exception e) {
        	System.out.println(e.getMessage());
            return ResponseBodyResult.error("取消关注失败!", e);

        }


    }
    
    
	/**
	 *  患者 关注 /取消关注 医生.非好友
	 * @param doctorid
	 * @param patientid
	 * @return
	 */
    @RequestMapping(value = "/followDoctor", method = RequestMethod.POST)
    public JSONObject followDoctor(@RequestParam Integer doctorid, @RequestParam Integer  patientid) {
        try {
        		//判断是否已经关注.
        	    Map<String, Object> map=new HashMap<>();
        	    map.put("doctorid", doctorid);
        	    map.put("patientid", patientid);
        		Integer id=doctorService.getFollow(map);
        		Integer result=0;
        		if(id==null) {
        			result=doctorService.saveFollow(map);
        			if(result>0) {
//        				doctorService.updateDoctorConcern(doctorid,1);
        				return ResponseBodyResult.success("关注成功");
        			}else {
        				return ResponseBodyResult.fail("关注失败");
        			}
        		}else {
        			result=doctorService.deleteFollow(id);
        			if(result>0) {
 //       				doctorService.updateDoctorConcern(doctorid,-1);
        				return ResponseBodyResult.success("取消关注成功");
        			}else {
        				return ResponseBodyResult.fail("取消关注失败");
        			}
        		}
        } catch (Exception e) {
            return ResponseBodyResult.error("取消关注失败!", e);
        }
    }
    
    
	/**
	 * @param @param  patientid
	 * @param @return 参数
	 * @return JSONObject    返回类型
	 * @throws
	 * @Title: myDoctorList
	 * @Description: 我关注的医生列表
	 */
	@RequestMapping(value = "/followDoctorList", method = RequestMethod.POST)
	public JSONObject followDoctorList(@RequestParam Integer patientid) {
		try {
			List<Map<String, Object>> myDorctorList = new ArrayList<Map<String, Object>>();
			List<Doctor> doctorList = doctorService.followDoctorList(patientid);
			// 获取最新关注医生的信息
			if (doctorList != null && doctorList.size() > 0) {
				for (Doctor doctor : doctorList) {
					Map<String, Object> mapResult = new HashMap<String, Object>();
					if (StringUtils.isEmpty(doctor.getAvatar())) {
						String defaultDoctor = SysConfigUtils
								.getConfigValue(AppEnum.sysConfig.DOCTOR_AVATAR_ALIYUN_URL.name());
						doctor.setAvatar(defaultDoctor);
					}

					List<Disease> diseaseList = doctorService.getDiseaseByDoctorId(doctor.getId());
					mapResult.put("diseaseList", diseaseList);
					mapResult.put("doctor", doctor);
					myDorctorList.add(mapResult);
				}
			}
			return ResponseBodyResult.success(myDorctorList);
		} catch (Exception e) {
			return ResponseBodyResult.error("查询失败!", e);
		}
	}
	
	
/**
 * 获得患者关注的医生ID集合 MAP返回
 * @param patientid
 * @return
 */
	@RequestMapping(value = "/followDoctorIDS", method = RequestMethod.POST)
	public JSONObject followDoctorIDS(@RequestParam Integer patientid) {
		try {
			List<Doctor> doctorList = doctorService.followDoctorList(patientid);
			Map<Integer, Integer> map=new HashMap<>();
			doctorList.forEach(m->{
					map.put(m.getId(), m.getId());
			});
			return ResponseBodyResult.success(map);
		} catch (Exception e) {
			return ResponseBodyResult.error("查询失败!", e);
		}
	}
	
	/**
	 * 
	    * @Title: getMyEvaluate  
	    * @Description: 我的评价
	    * @param @return    参数  
	    * @return JSONObject    返回类型  	`
	    * @throws
	 */
    @RequestMapping(value = "/getMyEvaluate", method = RequestMethod.GET)
    public JSONObject getMyEvaluate(Integer userId) {
        try {
            List<DoctorEvaluate> doctorEvaluateList =doctorService.getMyEvaluate(userId);
            return ResponseBodyResult.success(doctorEvaluateList);
        } catch (Exception e) {
            return ResponseBodyResult.error("医生评分查询失败!", e);

        }

    }
    
}
